import React, { useState, useRef, useCallback, useMemo } from 'react';
import { View, Text, TouchableOpacity, Image, ImageBackground, ScrollView, Modal, StyleSheet, Dimensions, Animated, Easing } from 'react-native';
import { AppStyles, AppColors, TextStyles } from '../../theme/uiLib.config';
import { useRouter } from 'expo-router';
import Icon from 'react-native-vector-icons/Ionicons';
import { Colors } from 'react-native-ui-lib';
import GetMorePointsModal from '../../components/GetMorePointsModal';

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');
const bottomSheetHeight = screenHeight * 0.65;

const AddInsurance = () => {
    const router = useRouter();
    const [insuranceDetails, setInsuranceDetails] = useState('');
    const [agreementChecked, setAgreementChecked] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [bottomSheetVisible, setBottomSheetVisible] = useState(false);
    const bottomSheetAnim = useRef(new Animated.Value(0)).current;
    const [selectedInsuredIds, setSelectedInsuredIds] = useState<number[]>([]);
    const [tempSelectedInsuredIds, setTempSelectedInsuredIds] = useState<number[]>([]);
    const [insufficientPointsModalVisible, setInsufficientPointsModalVisible] = useState(false);
    const [insufficientPointsMessage, setInsufficientPointsMessage] = useState('');
    const [getMorePointsModalVisible, setGetMorePointsModalVisible] = useState(false);

    // 被保人列表
    const [availableInsuredPersons, setAvailableInsuredPersons] = useState([
        { id: 1, name: '*磊（本人）', idCard: '429************259' },
        { id: 2, name: '*泉（父母）', idCard: '429************437' },
        { id: 3, name: '*兰（父母）', idCard: '429************668' },
    ]);

    // 管理被保障人列表
    const [insuredPersons, setInsuredPersons] = useState<{ id: number, name: string }[]>([]);

    const handleDelete = (id: number) => {
        // 删除被保障人
        setInsuredPersons(insuredPersons.filter(person => person.id !== id));
        setSelectedInsuredIds(prev => prev.filter(item => item !== id)); // 更新选中状态
    };

    const handleSubmit = () => {
        // 提交逻辑
        if (!agreementChecked) {
            alert('请阅读并同意相关协议');
            return;
        }
        console.log('提交保险信息:', insuranceDetails);
        // 这里可以添加导航到其他页面的逻辑
    };

    const handleInfoPress = () => {
        setModalVisible(true);
    };

    const closeModal = () => {
        setModalVisible(false);
    };

    const handleAddInsuredPress = useCallback(() => {
        setBottomSheetVisible(true);
        setTempSelectedInsuredIds([...selectedInsuredIds]);
        Animated.timing(bottomSheetAnim, {
            toValue: 1,
            duration: 300,
            easing: Easing.ease,
            useNativeDriver: false,
        }).start();
    }, [bottomSheetAnim, selectedInsuredIds]);

    const closeBottomSheet = useCallback(() => {
        Animated.timing(bottomSheetAnim, {
            toValue: 0,
            duration: 300,
            easing: Easing.ease,
            useNativeDriver: false,
        }).start(() => {
            setBottomSheetVisible(false);
        });
    }, [bottomSheetAnim]);

    const confirmAddInsured = useCallback(() => {
        const selectedPersons = availableInsuredPersons.filter(person => tempSelectedInsuredIds.includes(person.id));
        const selectedCount = selectedPersons.length;
        const totalPointsNeeded = selectedCount * 5000;
        const availablePoints = 13721; 

        setInsuredPersons(selectedPersons.map(person => ({ id: person.id, name: person.name })));
        setSelectedInsuredIds([...tempSelectedInsuredIds]);

        if (selectedCount === 3 && availablePoints < totalPointsNeeded) {
            setInsufficientPointsMessage(`兑换 ${selectedCount} 份万户保需要 ${totalPointsNeeded} 万户分，您当前只有 ${availablePoints} 万户分`);
            setInsufficientPointsModalVisible(true);
        }
        closeBottomSheet();
    }, [tempSelectedInsuredIds, availableInsuredPersons, closeBottomSheet]);

    const toggleInsuredSelection = (id: number) => {
        if (tempSelectedInsuredIds.includes(id)) {
            setTempSelectedInsuredIds(prev => prev.filter(item => item !== id));
        } else {
            setTempSelectedInsuredIds(prev => [...prev, id]);
        }
    };

    const bottomSheetStyle = {
        transform: [{
            translateY: bottomSheetAnim.interpolate({
                inputRange: [0, 1],
                outputRange: [bottomSheetHeight, 0],
            }),
        }],
    };

    const selectedCount = useMemo(() => insuredPersons.length, [insuredPersons]);
    const totalPoints = useMemo(() => selectedCount * 5000, [selectedCount]);
    const availablePoints = 13721;
    const insufficientPoints = useMemo(() => selectedCount === 3 && availablePoints < totalPoints, [selectedCount, totalPoints, availablePoints]);
    const phone = '133****7323';

    const pointsSource = useMemo(() => {
        if (insuredPersons.length === 0) {
            return null;
        }
        const firstPhonePoints = Math.round(totalPoints * 0.7);
        const secondPhonePoints = totalPoints - firstPhonePoints;
        return {
            firstPhonePoints,
            secondPhonePoints,
        };
    }, [insuredPersons, totalPoints]);


    return (
        <View style={[{ flex: 1, backgroundColor: AppColors.white }]}>
            <View style={{ position: 'absolute', top: 46, left: 12, zIndex: 100 }}>
                <TouchableOpacity onPress={() => router.push('/')}>
                    <Icon name="chevron-back-outline" size={24} color={AppColors.tertiary} />
                </TouchableOpacity>
            </View>

            <ScrollView>
                {/* 顶部头图 */}
                <View style={{ position: 'relative' }}>
                    <ImageBackground
                        source={require('../../../assets/images/insureheadpic.png')} 
                        style={{ width: '100%', height: undefined, aspectRatio: 1.35 }}
                        resizeMode="cover"
                    />
                    <View style={{ position: 'absolute', bottom: 20, right: 20 }}>
                        <TouchableOpacity
                            style={{
                                backgroundColor: AppColors.primary,
                                borderWidth: 1,
                                borderColor: AppColors.white,
                                borderRadius: 24,
                                paddingVertical: 10,
                                paddingHorizontal: 20,
                            }}
                            onPress={() => {
                                router.push('/Insure/InsuranceDetail');
                            }}
                        >
                            <Text style={[TextStyles.h3, { color: '#fff' }]}>查看详情</Text>
                        </TouchableOpacity>
                    </View>
                </View>

                <View style={[AppStyles.pagePadding]}>
                    {/* 所需积分 */}
                    <View style={{ flexDirection: 'row', alignItems: 'center', marginLeft: 20 }}>
                        <Text style={[TextStyles.number, { fontSize: 50, color: AppColors.golden, marginTop: 8 }]}>5000</Text>
                        <Text style={[TextStyles.h3, { color: AppColors.tertiary, marginLeft: 5, marginTop: 16 }]}>万户分/份</Text>
                    </View>

                    <View style={{ flexDirection: 'column', alignItems: 'flex-start', marginLeft: 20, marginRight: 20 }}>
                        <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 20 }}>
                            <Text style={[TextStyles.smallBold, {
                                width: 20,
                                height: 20,
                                backgroundColor: AppColors.primary,
                                borderRadius: 12,
                                color: AppColors.white,
                                textAlign: 'center',
                                lineHeight: 20,
                                marginRight: 4,
                            }]}>1</Text>
                            <Text style={[TextStyles.primaryBold, { color: AppColors.tertiary }]}>被保障人</Text>
                        </View>

                        {insuredPersons.map(person => (
                            <TouchableOpacity
                                key={person.id}
                                style={{
                                    borderWidth: 0.5,
                                    borderColor: AppColors.orange1,
                                    borderRadius: 6,
                                    justifyContent: 'space-between',
                                    alignItems: 'center',
                                    width: '100%',
                                    height: 50,
                                    backgroundColor: Colors.orange2,
                                    marginTop: 12,
                                    flexDirection: 'row', // 使用行方向排列
                                    paddingHorizontal: 20, // 添加左右内边距
                                }}
                                onPress={() => {
                                    console.log(`被保人${person.id}`);
                                }}
                            >
                                <Text style={[TextStyles.smallBold, { color: AppColors.orange1 }]}>{person.name}</Text>
                                <TouchableOpacity
                                    style={{
                                        backgroundColor: 'transparent',
                                        width: 46,
                                        height: 40,
                                        alignItems: 'flex-end',
                                        justifyContent: 'center',

                                    }}
                                    onPress={() => handleDelete(person.id)}>
                                    <Text style={[TextStyles.small, { color: AppColors.secondary }]}>删除</Text>
                                </TouchableOpacity>
                            </TouchableOpacity>
                        ))}

                        <TouchableOpacity
                            style={{
                                borderRadius: 6,
                                justifyContent: 'center',
                                width: '100%',
                                height: 46,
                                backgroundColor: AppColors.grey11,
                                marginTop: 12,
                            }}
                            onPress={handleAddInsuredPress}
                        >
                            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                                <Icon name="add-circle-outline" size={18} color={AppColors.tertiary} style={{ marginRight: 3 }} />
                                <Text style={[TextStyles.small, { color: AppColors.tertiary }]}>添加/修改被保人</Text>
                            </View>
                        </TouchableOpacity>


                        <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 50 }}>
                            <Text style={[TextStyles.smallBold, {
                                width: 20,
                                height: 20,
                                backgroundColor: AppColors.primary,
                                borderRadius: 12,
                                color: AppColors.white,
                                textAlign: 'center',
                                lineHeight: 20,
                                marginRight: 4,
                            }]}>2</Text>
                            <Text style={[TextStyles.primaryBold, { color: AppColors.tertiary }]}>所需积分</Text>
                        </View>
                        <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 4, flexWrap: 'wrap' }}>
                            <Text style={[TextStyles.number, { fontSize: 20, color: AppColors.tertiary, marginTop: 2 }]}>{selectedCount}</Text>
                            <Text style={[TextStyles.primary, { color: AppColors.tertiary, marginLeft: 5 }]}>份 合计共：</Text>
                            <Text style={[TextStyles.number, { fontSize: 36, color: AppColors.golden, marginBottom: 4 }]}>{totalPoints}</Text>
                            <Text style={[TextStyles.primary, { color: AppColors.tertiary, marginLeft: 5 }]}>万户分</Text>
                            {insufficientPoints && (
                                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                    <Text style={[TextStyles.smallBold, { color: AppColors.accent }]}>
                                        积分不足！当前仅有{availablePoints}分
                                    </Text>
                                    <TouchableOpacity
                                        style={{
                                            marginLeft: 6,
                                            backgroundColor: AppColors.success,
                                            borderRadius: 12,
                                            paddingVertical: 4,
                                            paddingHorizontal: 8,
                                        }}
                                        onPress={() => {
                                            setGetMorePointsModalVisible(true);
                                        }}>

                                        <Text style={[TextStyles.smallBold, { color: AppColors.white }]}>获取更多积分！</Text>
                                    </TouchableOpacity>
                                </View>
                            )}


                        </View>

                        {pointsSource && (
                            <View>
                                <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 30 }}>
                                    <Text style={[TextStyles.smallBold, {
                                        width: 20,
                                        height: 20,
                                        backgroundColor: AppColors.primary,
                                        borderRadius: 12,
                                        color: AppColors.white,
                                        textAlign: 'center',
                                        lineHeight: 20,
                                        marginRight: 4,
                                    }]}>3</Text>
                                    <Text style={[TextStyles.primaryBold, { color: AppColors.tertiary }]}>积分来源：</Text>
                                    <TouchableOpacity onPress={handleInfoPress}>
                                        <Icon name="information-circle" size={26} color={AppColors.secondary} />
                                    </TouchableOpacity>
                                </View>
                                <View style={{ flexDirection: 'column', alignItems: 'flex-start', marginTop: 4 }}>
                                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                        <Text style={[TextStyles.smaller, { paddingVertical: 2, paddingHorizontal: 9, backgroundColor: AppColors.secondary, borderRadius: 10, color: AppColors.white }]}>138****8000</Text>
                                        <Text style={[TextStyles.small, { color: AppColors.tertiary }]}> 提供 {pointsSource.firstPhonePoints}万户分</Text>
                                    </View>
                                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                        <Text style={[TextStyles.smaller, { paddingVertical: 2, paddingHorizontal: 9, backgroundColor: AppColors.secondary, borderRadius: 10, color: AppColors.white }]}>135****9000</Text>
                                        <Text style={[TextStyles.small, { color: AppColors.tertiary }]}> 提供 {pointsSource.secondPhonePoints}万户分</Text>
                                    </View>
                                </View>
                            </View>
                        )}
                    </View>

                    {/* 提交按钮 */}
                    <View style={{ alignItems: 'center', marginTop: 40, marginBottom: 140 }}>
                        <View style={{ flexDirection: 'row', alignItems: 'flex-start', marginBottom: 10, width: '90%' }}>
                            <TouchableOpacity
                                style={{
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    width: 20,
                                    height: 20,
                                    borderRadius: 10,
                                    marginRight: 8,
                                    backgroundColor: agreementChecked ? AppColors.primary : Colors.grey20,
                                }}
                                onPress={() => setAgreementChecked(!agreementChecked)}
                            >
                                {agreementChecked && <Icon name="checkmark-sharp" size={16} color={Colors.white} />}
                                {!agreementChecked && <Icon name="checkmark-sharp" size={16} color={Colors.grey10} />}
                            </TouchableOpacity>
                            <Text style={[TextStyles.small, { color: AppColors.secondary, lineHeight: 22 }]}>
                                我已阅读并同意
                                <Text style={[TextStyles.small, { color: AppColors.tertiary }]} onPress={() => { console.log('《万户健康公益项目服务协议》') }}>《万户健康公益项目服务协议》</Text>
                                及
                                <Text style={[TextStyles.small, { color: AppColors.tertiary }]} onPress={() => { console.log('《授权委托书》') }}>《授权委托书》</Text>
                            </Text>
                        </View>
                        <TouchableOpacity
                            style={{
                                marginTop: 10,
                                alignSelf: 'center',
                                justifyContent: 'center',
                                width: '90%',
                                height: 60,
                                backgroundColor: insufficientPoints ? Colors.grey30 : AppColors.primary,
                                borderRadius: 24,
                            }}
                            onPress={handleSubmit}
                            disabled={insufficientPoints}
                        >
                            <Text style={[TextStyles.h2, { color: '#fff', textAlign: 'center' }]}>同意条款并领取</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </ScrollView>
            <Modal
                transparent={true}
                animationType="fade"
                visible={modalVisible}
            >
                <View style={styles.modalOverlay}>
                    <View style={styles.modalContent}>
                        <Text style={[TextStyles.h3, { alignSelf: 'center', marginBottom: 20 }]}>万户分兑换使用说明</Text>
                        <Text style={[TextStyles.primary, { lineHeight: 30 }]}>
                            在兑换保险时，系统将依据所需万户分数量，自动扫描已绑定家庭成员账号。综合各商户的积分兑换规则与可兑换度，智能选择合适商户，将其积分转换为万户分，以精准满足本次保险兑换需求，便捷完成支付流程。
                        </Text>
                        <TouchableOpacity style={[styles.closeButton, { width: '100%', height: 40, borderRadius: 24, borderWidth: 1, borderColor: AppColors.primary, backgroundColor: AppColors.white, alignItems: 'center', justifyContent: 'center' }]} onPress={closeModal}>
                            <Text style={[TextStyles.small, { color: AppColors.primary }]}>关闭</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </Modal>
            {bottomSheetVisible && (
                <View style={styles.bottomSheetOverlay}>
                    <Animated.View style={[styles.bottomSheetContainer, bottomSheetStyle]}>
                        <View style={styles.bottomSheetHeader}>
                            <TouchableOpacity onPress={closeBottomSheet}>
                                <Text style={[TextStyles.primary, { color: AppColors.tertiary }]}>取消</Text>
                            </TouchableOpacity>
                            <Text style={[TextStyles.h3, { flex: 1, textAlign: 'center' }]}>添加被保人</Text>
                            <TouchableOpacity onPress={confirmAddInsured}>
                                <Text style={[TextStyles.primary, { color: AppColors.primary }]}>确定</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={styles.bottomSheetContent}>
                            {availableInsuredPersons.map(person => (
                                <TouchableOpacity
                                    key={person.id}
                                    style={[
                                        styles.bottomSheetItem,
                                        tempSelectedInsuredIds.includes(person.id) ? styles.bottomSheetItemSelected : styles.bottomSheetItemUnselected
                                    ]}
                                    onPress={() => toggleInsuredSelection(person.id)}
                                >
                                    <View style={[styles.bottomSheetCheckbox, tempSelectedInsuredIds.includes(person.id) && styles.bottomSheetCheckboxChecked]}>
                                        {tempSelectedInsuredIds.includes(person.id) && <Icon name="checkmark-sharp" size={16} color={Colors.white} />}
                                    </View>
                                    <View style={styles.bottomSheetItemTextContainer}>
                                        <Text style={[TextStyles.primary, tempSelectedInsuredIds.includes(person.id) && { color: AppColors.orange1 }]}>{person.name}</Text>
                                        <Text style={[TextStyles.small, tempSelectedInsuredIds.includes(person.id) && { color: AppColors.orange1 }]}>{person.idCard}</Text>
                                    </View>
                                </TouchableOpacity>
                            ))}
                        </View>
                    </Animated.View>
                </View>
            )}
            <Modal
                transparent={true}
                animationType="fade"
                visible={insufficientPointsModalVisible}
            >
                <View style={styles.modalOverlay}>
                    <View style={styles.modalContent}>
                        <Text style={[TextStyles.h3, { alignSelf: 'center', marginBottom: 20 }]}>积分不足！</Text>
                        <Text style={[TextStyles.primary, { alignSelf: 'center', marginBottom: 20 }]}>{insufficientPointsMessage}</Text>
                        <View style={{ flexDirection: 'row', justifyContent: 'space-around' }}>
                            <TouchableOpacity style={[styles.closeButton, { width: '30%', height: 40, borderRadius: 24, borderWidth: 1, borderColor: AppColors.primary, backgroundColor: AppColors.white, alignItems: 'center', justifyContent: 'center' }]} onPress={() => setInsufficientPointsModalVisible(false)}>
                                <Text style={[TextStyles.small, { color: AppColors.primary }]}>返回</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={[styles.closeButton, { width: '50%', height: 40, borderRadius: 24, borderWidth: 1, borderColor: AppColors.success, backgroundColor: AppColors.success, alignItems: 'center', justifyContent: 'center' }]} onPress={() => {
                                setInsufficientPointsModalVisible(false);
                                setGetMorePointsModalVisible(true);
                            }}>
                                <Text style={[TextStyles.smallBold, { color: AppColors.white }]}>获取更多积分</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>
            <GetMorePointsModal
                isVisible={getMorePointsModalVisible}
                onClose={() => setGetMorePointsModalVisible(false)}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    modalOverlay: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.7)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    modalContent: {
        backgroundColor: 'white',
        padding: 20,
        borderRadius: 10,
        width: '80%',
    },
    closeButton: {
        marginTop: 40,
        marginBottom: 10,
        alignSelf: 'flex-end',
    },
    bottomSheetOverlay: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: 'rgba(0, 0, 0, 0.7)',
        zIndex: 10,
    },
    bottomSheetContainer: {
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'white',
        height: bottomSheetHeight,
        borderTopLeftRadius: 12,
        borderTopRightRadius: 12,
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: -2,
        },
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5,
    },
    bottomSheetHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 20,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    bottomSheetContent: {
        padding: 20,
        flex: 1,
        justifyContent: 'flex-start',
    },
    bottomSheetItem: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 10,
        paddingHorizontal: 10,
        borderRadius: 8,
        marginBottom: 8,
        height: 80,
    },
    bottomSheetItemUnselected: {
        backgroundColor: '#f0f0f0',
    },
    bottomSheetItemSelected: {
        backgroundColor: Colors.orange2,
        borderWidth: 0.5,
        borderColor: AppColors.orange1,
    },
    bottomSheetCheckbox: {
        width: 20,
        height: 20,
        borderRadius: 4,
        borderWidth: 0.5,
        borderColor: AppColors.grey20,
        marginRight: 10,
        justifyContent: 'center',
        alignItems: 'center',
    },
    bottomSheetCheckboxChecked: {
        backgroundColor: AppColors.orange1,
        borderColor: AppColors.orange1,
    },
    bottomSheetItemTextContainer: {
        flexDirection: 'column',
    },
});

export default AddInsurance;